package com.cy.controller;

import com.cy.Service.DeptService;
import com.cy.entity.Dept;
import com.cy.entity.Emp;
import com.cy.entity.Sex;
import com.cy.entity.Tj;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class DeptController {
    @Autowired
    DeptService service;
    @RequestMapping("list")
    public String list(Tj tj, @RequestParam(defaultValue = "1") Integer pageNum, Model model){
        PageInfo<Emp> page = service.list(tj,pageNum);
        model.addAttribute("pg",page);
        model.addAttribute(tj);
        List<Dept> list = service.dept();
        model.addAttribute("dept",list);
        return "list";
    }
    @RequestMapping("del")
    public String del(Integer id){
        service.del(id);
        return "redirect:list";
    }
    @RequestMapping("add")
    public String add(Model model){
        model.addAttribute("emp",new Emp());
        model.addAttribute("sex", Sex.values());
        model.addAttribute("dept",service.dept());
        return "insert";
    }
    @RequestMapping("insert")
    public String insert(@Validated @ModelAttribute Emp emp, BindingResult result, Model model){
        if(result.hasErrors()){
            model.addAttribute("sex", Sex.values());
            model.addAttribute("dept",service.dept());
            return "insert";
        }
        service.insert(emp);
        return "redirect:list";
    }
    @RequestMapping("up")
    public String up(Integer id,Model model){
        Emp emp = service.sel(id);
        model.addAttribute("emp",emp);
        model.addAttribute("sex", Sex.values());
        model.addAttribute("dept",service.dept());
        return "update";
    }
    @RequestMapping("update")
    public String update(@Validated @ModelAttribute Emp emp,BindingResult result,Model model){
        if(result.hasErrors()){
            model.addAttribute("sex", Sex.values());
            model.addAttribute("dept",service.dept());
            return "update";
        }
        service.update(emp);
        return "redirect:list";
    }
}
